package com.slg.android.manyanime;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.slg.android.manyanime.adapter.WatchUserAdapter;
import com.slg.android.manyanime.bean.AnimationDetail;
import com.slg.android.manyanime.bean.Collection;
import com.slg.android.manyanime.bean.Episode;
import com.slg.android.manyanime.bean.User;
import com.slg.android.manyanime.fragment.AnimationDetailIntroFragment;
import com.slg.android.manyanime.fragment.EpisodeFragment;
import com.slg.android.manyanime.utils.ApiUtils;
import com.slg.android.manyanime.utils.DataStore;
import com.slg.android.manyanime.utils.NetUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


public class AnimationDetailActivity extends FragmentActivity {
    @ViewInject(R.id.common_collect_imageView)
    private ImageView collect;
    @ViewInject(R.id.common_share_imageView)
    private ImageView share;
    @ViewInject(R.id.animation_detail_pic_imageView)
    private ImageView pic;
    @ViewInject(R.id.animation_detail_name_textView)
    private TextView name;
    @ViewInject(R.id.animation_detail_area_textView)
    private TextView area;
    @ViewInject(R.id.animation_detail_character_textView)
    private TextView character;
    @ViewInject(R.id.animation_detail_update_textView)
    private TextView update;
    @ViewInject(R.id.animation_detail_publish_textView)
    private TextView publish;
    @ViewInject(R.id.animation_detail_intro_textView)
    private TextView intro;
    @ViewInject(R.id.animation_detail_comment_textView)
    private TextView comment;
    @ViewInject(R.id.animation_detail_episode_textView)
    private TextView episode;
    @ViewInject(R.id.animation_detail_score_textView)
    private TextView score;
    @ViewInject(R.id.animation_detail_looking)
    private RecyclerView looking;
    @ViewInject(R.id.animation_detail_score_imageView)
    private ImageView scoreImage;
    @ViewInject(R.id.common_loading)
    private RelativeLayout loading;
    @ViewInject(R.id.common_loading_image)
    private ImageView loadingImage;
    private Animation animation;
    private String id;
    private User user;
    private FragmentManager fragmentManager;
    private AnimationDetail detail;
    private final String IntroFragmentTag = "IntroFragment";
    private final String EpisodeFragmentTag = "EpisodeFragment";
    private DbUtils db;
    private boolean collected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_animation_detail);
        ViewUtils.inject(this);
        db = DataStore.getDataStore().getDb();
        LinearLayoutManager layout = new LinearLayoutManager(AnimationDetailActivity.this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        looking.setLayoutManager(layout);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        if (TextUtils.isEmpty(id)) {
            name.setText(R.string.video_id_not_found);
            scoreImage.setImageResource(R.drawable.face_1);
        } else {
            try {
                List<Collection> all = db.findAll(Collection.class);
                if (all != null) {
                    for (Collection collection : all) {
                        if(TextUtils.equals(id,collection.getId())){
                            collect.setImageResource(R.drawable.cancel_fav);
                            collected = true;
                            break;
                        }
                    }
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
            if (NetUtil.isConnectInternet(this)) {
                fragmentManager = getSupportFragmentManager();
                //开启加载动画
                animation = AnimationUtils.loadAnimation(this, R.anim.anim_common_rotate);
                loading.setVisibility(View.VISIBLE);
                loadingImage.startAnimation(animation);
                HttpUtils utils = new HttpUtils();
                User user = DataStore.getDataStore().getUser();
                String uid = "";
                if (user != null) {
                    uid = user.getId();
                }
                utils.send(HttpRequest.HttpMethod.GET
                        , ApiUtils.ANIMATION_DETAIL + id + "&uid=" + uid
                        , new CallBack());

            } else {
                name.setText(R.string.no_network);
                scoreImage.setImageResource(R.drawable.face_1);
            }
        }

    }

    @Override
    protected void onResume() {
        user = DataStore.getDataStore().getUser();
        super.onResume();
    }

    @OnClick({R.id.common_back_imageView, R.id.common_collect_imageView
            , R.id.common_share_imageView, R.id.animation_detail_intro_textView
            , R.id.animation_detail_comment_textView, R.id.animation_detail_episode_textView})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.common_back_imageView) {
            finish();
        }
        if (!TextUtils.isEmpty(id)) {
            switch (viewId) {
                case R.id.animation_detail_intro_textView:
                    intro.setTextColor(getResources().getColor(R.color.main_menu_text_selected));
                    episode.setTextColor(getResources().getColor(R.color.common_text_title_color));
                    displayFragment(IntroFragmentTag);
                    break;
                case R.id.animation_detail_episode_textView:
                    episode.setTextColor(getResources().getColor(R.color.main_menu_text_selected));
                    intro.setTextColor(getResources().getColor(R.color.common_text_title_color));
                    displayFragment(EpisodeFragmentTag);
                    break;
                case R.id.animation_detail_comment_textView:
                    Intent intent = new Intent(this, CommentActivity.class);
                    intent.putExtra("mid", id);
                    intent.putExtra("type", "video");
                    startActivity(intent);
                    break;
                case R.id.common_collect_imageView:
                    if(collected){
                        try {
                            collected = false;
                            db.delete(Collection.class, WhereBuilder.b("id","=",id));
                            Toast.makeText(this,"已从收藏中移除",Toast.LENGTH_SHORT).show();
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        collect.setImageResource(R.drawable.bt_main_fav);
                    }else {
                        try {
                            Collection collection = new Collection();
                            collection.setPic(detail.getVideoId());
                            collection.setPic(detail.getCover());
                            collection.setIsOver(detail.getIsOver());
                            collection.setLastUp(detail.getCurNum());
                            collection.setCurNum(detail.getCurNum());
                            collection.setType("video");
                            collection.setName(detail.getName());
                            collection.setTotalNum(detail.getTotalNum());
                            collection.setId(id);
                            db.saveBindingId(collection);
                            collected = true;
                            collect.setImageResource(R.drawable.cancel_fav);
                            Toast.makeText(this,"已添加到收藏",Toast.LENGTH_SHORT).show();
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                //TODO 分享点击事件
            }
        }
    }

    private void displayFragment(String tag) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag(tag);
        if (fragment != null) {
            Log.d("fragment ", "exist");
            transaction.replace(R.id.animation_detail_fragment_container
                    , fragment);
        } else {
            if (IntroFragmentTag.equals(tag)) {
                AnimationDetailIntroFragment introFragment =
                        new AnimationDetailIntroFragment();
                Bundle args = new Bundle();
                args.putString("intro", detail.getIntro());
                introFragment.setArguments(args);
                transaction.replace(R.id.animation_detail_fragment_container
                        , introFragment, tag);
            } else {
                EpisodeFragment episodeFragment = new EpisodeFragment();
                Bundle args = new Bundle();
                args.putSerializable("episode",
                        (ArrayList<Episode>) detail.getEpisodes());
                episodeFragment.setArguments(args);
                transaction.replace(R.id.animation_detail_fragment_container
                        , episodeFragment, tag);
            }
        }
        transaction.commit();
    }

    private class CallBack extends RequestCallBack<String> {
        @Override
        public void onSuccess(ResponseInfo<String> objectResponseInfo) {
            String json = objectResponseInfo.result;
            detail = AnimationDetail.parseData(json);
            BitmapUtils bitmapUtils = DataStore.getBitmapUtils();
            bitmapUtils.display(pic, detail.getCover());
            name.setText(detail.getName());
            area.setText("地区：" + detail.getArea());
            if (TextUtils.isEmpty(detail.getCharacter())) {
                character.setText("主演：暂无");
            } else {
                character.setText("主演：" + detail.getCharacter());
            }
            String updateString = "未知";
            if (!TextUtils.isEmpty(detail.getUpdateString())) {
                updateString = detail.getUpdateString();
            }
            if ("1".equals(detail.getIsOver())) {//已完结
                update.setText("更新时间：" + updateString + "(全" + detail.getTotalNum()
                        + "集)");
            } else {
                update.setText("更新时间：" + updateString
                        + "(更新至" + detail.getCurNum() + "集)");
            }
            publish.setText("上映时间：" + detail.getPublishTime());
            //设置评分
            float detailScore = 0.0f;
            if(!TextUtils.isEmpty(detail.getScore())){
                detailScore = Float.parseFloat(detail.getScore());
            }else{
                int totalNum = Integer.parseInt(detail.getScoreTotalNum());
                int personNum = Integer.parseInt(detail.getScorePersonNum());
                detailScore = (float) (totalNum / personNum *1.0);
                String s =  new DecimalFormat("###,###,###.#").format(detailScore);
                detail.setScore(s);
            }
            score.setText(detail.getScore() + "分");
            if (detailScore >= 9) {
                scoreImage.setImageResource(R.drawable.face_5);
            } else if (detailScore >= 8) {
                scoreImage.setImageResource(R.drawable.face_4);
            } else if (detailScore >= 7) {
                scoreImage.setImageResource(R.drawable.face_3);
            } else {
                scoreImage.setImageResource(R.drawable.face_2);
            }
            //设置评论
            String commentNum = detail.getCommentNum();
            if (Integer.parseInt(commentNum) > 0) {
                comment.setText("评论(" + detail.getCommentNum() + ")");
            } else {
                comment.setText("评论");
            }

            //设置底部fragment
            displayFragment(IntroFragmentTag);
            WatchUserAdapter adapter =
                    new WatchUserAdapter(AnimationDetailActivity.this
                            , detail.getWatchUsers());
            looking.setAdapter(adapter);

            //取消加载动画
            animation.cancel();
            loading.setVisibility(View.GONE);
        }

        @Override
        public void onFailure(HttpException e, String s) {
            //取消加载动画
            animation.cancel();
            loading.setVisibility(View.GONE);
            name.setText(R.string.no_network);
            scoreImage.setImageResource(R.drawable.face_1);
        }
    }


}
